package cn.echoparrot.repository.neo4j;

import cn.echoparrot.domain.entity.DataFile;
import cn.echoparrot.domain.entity.Dataset;
import cn.echoparrot.domain.entity.Segment;
import org.neo4j.driver.Value;
import org.neo4j.driver.Values;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface DataFileMapper extends Neo4jRepository<DataFile, Long> {
    Logger logger = LoggerFactory.getLogger(DataFileMapper.class);
    default void saveEmbedding(DataFile dataFile) {
        // 从关联的Dataset中找到对应的知识库ID,将其作为；
        Dataset dataset = dataFile.dataset();
        logger.info("正在保存 {} 的嵌入向量,{}", dataFile.name(),dataFile.segments());
        for(Segment segment : dataFile.segments()){
            attachEmbedding(segment.id(), Values.value(segment.embedding()), dataset.labelName4Segment());
        }
    }

    /**
     *
     * @param embeddingLabel Segment的第二个Label，用于针对某个知识库的特定索引。
     */
    @Query("MATCH (s:Segment) WHERE id(s) = $id " +
           "SET s:`:#{literal(#embeddingLabel)}` " +
           "WITH s " +
           "CALL db.create.setNodeVectorProperty(s, 'embedding', $embeddingValue) " +
           "RETURN s")
    void attachEmbedding(Long id, Value embeddingValue, String embeddingLabel );


    @Query("""
                            MATCH (d:Dataset)-[:HAS_FILE]->(f:File {name: $filename})-[]->(s:Segment)
                            WHERE id(d) = $datasetId
                            DETACH DELETE s
                            DETACH DELETE f
                            """)
    void deleteFile(Long datasetId, String filename);
}